/**
 * Licensed to CMIM,Inc. under the terms of the CMIM * Software License version 1.0.
 * See the NOTICE file distributed with this work for additional * information regarding copyright ownership.
 * ---------------------------------------------------------------------------- * Date Author Version
 * 2019/3/16 neusoft 1.0
 **/

package com.xnyzc.lhy.common.util.http;


import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

public class HttpRequestUtil {

    public static final String REQUEST_TYPE_GET = "get";
    public static final String REQUEST_TYPE_POST = "post";


    /**
     * 模拟发出Http请求
     *
     * @param uri      请求资源,如：http://www.baidu.com/,注意严谨的格式
     * @param params   请求参数
     * @param type     请求方式,目前只支持get/post
     * @param encoding 网页编码
     * @return HttpResponseBody
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String request(String uri, Map<String, Object> params, String type, String encoding) throws ClientProtocolException, IOException {
        String result = "";
        //String apiName=uri;

        HttpResponse httpResponse = null;

        // GET方式请求
        if (HttpRequestUtil.REQUEST_TYPE_GET.equals(type)) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                // 创建默认的httpClient实例.
                // 加入请求参数
                if (params != null) {
                    if (uri.indexOf('?') != -1) {
                        uri += "&";
                    } else {
                        uri += "?";
                    }
                    for (String key : params.keySet()) {

                        uri += key + "=" + params.get(key) + "&";
                    }
                }
                //LogWriter.writeApiResponseWorkLog(apiName, uri);  //api请求信息

                HttpGet httpGet = new HttpGet(uri);
                httpResponse = httpClient.execute(httpGet);
                // 获取返回内容
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    InputStream is = entity.getContent();
                 /*int l ;
                 byte[] buff = new byte[9192];
                 while( (l = is.read(buff)) != -1){
                     result += new String(buff, 0, l, encoding);
                 }*/
                    StringBuffer stringBuffer = new StringBuffer();
                    String line;
                    Reader reader = new InputStreamReader(is, encoding);
                    //增加缓冲功能
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                    result = stringBuffer.toString();
                }
            } catch (Exception e) {
                throw e;
            } finally {
                httpClient.close();
            }
            //LogWriter.writeApiResponseWorkLog(apiName, result);  //输出日志
            return result;
        } else {
            StringBuffer sb = new StringBuffer();
            Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }

            //LogWriter.writeApiResponseWorkLog(apiName, uri);  //api请求信息
            URL url = new URL(uri);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            OutputStream os = http.getOutputStream();
            String str = sb.substring(0, sb.length() - 1);
            os.write(str.getBytes(encoding));// 传入参数
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            Reader reader = new InputStreamReader(is, encoding);
            //增加缓冲功能
            BufferedReader bufferedReader = new BufferedReader(reader);
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            result = stringBuffer.toString();
			/*int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			result = new String(jsonBytes, encoding);*/
            //LogWriter.writeApiResponseWorkLog(apiName, result);  //输出日志
            return result;
        }
    }


    /**
     * 模拟发出Http请求
     *
     * @param uri      请求资源,如：http://www.baidu.com/,注意严谨的格式
     * @param params   请求参数
     * @param type     请求方式,目前只支持get/post
     * @param encoding 网页编码
     * @return HttpResponseBody
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String request1(String uri, Map<String, Object> params, String type, String encoding) throws ClientProtocolException, IOException {
        String result = "";
        //String apiName=uri;

        HttpResponse httpResponse = null;

        // GET方式请求
        if (HttpRequestUtil.REQUEST_TYPE_GET.equals(type)) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                // 创建默认的httpClient实例.
                // 加入请求参数
                if (params != null) {
                    if (uri.indexOf('?') != -1) {
                        uri += "&";
                    } else {
                        uri += "?";
                    }
                    for (String key : params.keySet()) {
                        uri += key + "=" + params.get(key) + "&";
                    }
                }
                //LogWriter.writeApiResponseWorkLog(apiName, uri);  //api请求信息

                HttpGet httpGet = new HttpGet(uri);
                httpResponse = httpClient.execute(httpGet);
                // 获取返回内容
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    InputStream is = entity.getContent();
                 /*int l ;
                 byte[] buff = new byte[9192];
                 while( (l = is.read(buff)) != -1){
                     result += new String(buff, 0, l, encoding);
                 }*/
                    StringBuffer stringBuffer = new StringBuffer();
                    String line;
                    Reader reader = new InputStreamReader(is, encoding);
                    //增加缓冲功能
                    BufferedReader bufferedReader = new BufferedReader(reader);
                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    if (bufferedReader != null) {
                        bufferedReader.close();
                    }
                    result = stringBuffer.toString();
                }
            } catch (Exception e) {
                throw e;
            } finally {
                httpClient.close();
            }
            //LogWriter.writeApiResponseWorkLog(apiName, result);  //输出日志
            return result;
        } else {
            StringBuffer sb = new StringBuffer();
            Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                sb.append("&");
            }

            //LogWriter.writeApiResponseWorkLog(apiName, uri);  //api请求信息
            URL url = new URL(uri);
            HttpURLConnection http = (HttpURLConnection) url.openConnection();

            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            OutputStream os = http.getOutputStream();

            String strParam = "SN=" + params.get("SN").toString() + "&" + "platform=" + params.get("platform").toString() + "&" + "TimeStamp=" + params.get("TimeStamp").toString()
                    + "&checkInfo=" + params.get("checkInfo").toString();
            os.write(strParam.getBytes(encoding));// 传入参数
            os.flush();
            os.close();

            InputStream is = http.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            String line;
            Reader reader = new InputStreamReader(is, encoding);
            //增加缓冲功能
            BufferedReader bufferedReader = new BufferedReader(reader);
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            result = stringBuffer.toString();
			/*int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			result = new String(jsonBytes, encoding);*/
            //LogWriter.writeApiResponseWorkLog(apiName, result);  //输出日志
            return result;
        }
    }

    /**
     * post方式请求
     *
     * @param uri
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String uri, Map<String, Object> params) throws ClientProtocolException, IOException {
        return request(uri, params, "post", "utf-8");
    }

    /**
     * get方式请求
     *
     * @param uri
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String get(String uri, Map<String, Object> params) throws ClientProtocolException, IOException {
        return request(uri, params, "get", "utf-8");
    }

    /**
     * post方式请求
     *
     * @param uri
     * @param params
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String postFile(String uri, Map<String, Object> params, String fileBase64) throws ClientProtocolException, IOException {

        // 加入请求参数
        if (params != null) {
            if (uri.indexOf('?') != -1) {
                uri += "&";
            } else {
                uri += "?";
            }
            for (String key : params.keySet()) {
                uri += key + "=" + params.get(key) + "&";
            }
        }

        String result = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse httpResponse = null;
        try {
            HttpPost httpPost = new HttpPost(uri);
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntityBuilder.addTextBody("fileBase64", fileBase64);//增加字节内容，第二个参数可以是File,byte[],InputStream

            httpPost.setEntity(multipartEntityBuilder.build());

            httpResponse = httpClient.execute(httpPost);

            // 获取返回内容
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                InputStream is = entity.getContent();
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                Reader reader = new InputStreamReader(is, "utf-8");
                //增加缓冲功能
                BufferedReader bufferedReader = new BufferedReader(reader);
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                result = stringBuffer.toString();
            }
        } catch (Exception e) {
            throw e;
        } finally {
            httpClient.close();
        }

        return result;
    }

    /**
     * 发出Http请求
     */
    public static String requestPost(String uri, String str) throws IOException {
        String encoding = "utf-8";
        String result = "";
        URL url = new URL(uri);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();

        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        http.setDoOutput(true);
        http.setDoInput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
        http.connect();
        OutputStream os = http.getOutputStream();
        os.write(str.getBytes(encoding));// 传入参数
        os.flush();
        os.close();

        InputStream is = http.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        Reader reader = new InputStreamReader(is, encoding);
        //增加缓冲功能
        BufferedReader bufferedReader = new BufferedReader(reader);
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        result = stringBuffer.toString();
        return result;
    }

    /**
     * 发出Http请求
     */
    public static String requestPostJson(String uri, JSONObject json) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(json.toString(), "UTF-8"));
        String s = json.toString();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        response.close();
        httpClient.close();
        return responseContent;
    }

    /**
     * 发出Http请求
     */
    public static String requestPostJson(String uri, String json) throws IOException {
        String encoding = "utf-8";
        String result = "";
        URL url = new URL(uri);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();

        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/json");
        http.setDoOutput(true);
        http.setDoInput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "20000");// 连接超时30秒
        System.setProperty("sun.net.client.defaultReadTimeout", "20000"); // 读取超时30秒
        http.connect();
        OutputStream os = http.getOutputStream();
        os.write(json.getBytes(encoding));// 传入参数
        os.flush();
        os.close();

        InputStream is = http.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        Reader reader = new InputStreamReader(is, encoding);
        //增加缓冲功能
        BufferedReader bufferedReader = new BufferedReader(reader);
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        result = stringBuffer.toString();
        return result;
    }

}

